/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.djnt.catering.database;

import java.util.HashMap;

import com.djnt.catering.HanziHelper;
import com.djnt.catering.Marshal;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;

/**
 * Provides access to a database of notes. Each note has a title, the note
 * itself, a creation date and a modified data.
 */
public class CateringProvider extends ContentProvider {

	private static final String TAG = "CateringProvider";
	public static final String AUTHORITY = "com.djnt.catering.CateringProvider";

	private DatabaseHelper mOpenHelper;

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int match = UriMatcherCode.match(uri);

		switch (match) {
		case UriMatcherCode.PROVINCE:
			qb.setTables(Province.TABLE_NAME);
			qb.setProjectionMap(Province.PROJECTION_MAP);
			break;
		case UriMatcherCode.CITY:
			qb.setTables(City.TABLE_NAME);
			qb.setProjectionMap(City.PROJECTION_MAP);
			break;

		case UriMatcherCode.PROVINCE_ID:
			qb.setTables(Province.TABLE_NAME);
			qb.setProjectionMap(Province.PROJECTION_MAP);
			qb.appendWhere(Province._ID + "=" + uri.getPathSegments().get(1));
			break;

		case UriMatcherCode.VIEW_CITY_PROVINCE:
			qb.setTables(ViewCityProvince.TABLE_NAME);
			qb.setProjectionMap(ViewCityProvince.PROJECTION_MAP);
			break;

		case UriMatcherCode.HOTNEWS:
			qb.setTables(HotNews.TABLE_NAME);
			qb.setProjectionMap(HotNews.PROJECTION_MAP);
			break;
		case UriMatcherCode.HOTNEWS_ID:
			qb.setTables(HotNews.TABLE_NAME);
			qb.setProjectionMap(HotNews.PROJECTION_MAP);
			qb.appendWhere(HotNews._ID + "=" + uri.getPathSegments().get(1));
			break;
		case UriMatcherCode.COMPANY_USERS:
			qb.setTables(CompanyUsers.TABLE_NAME);
			qb.setProjectionMap(CompanyUsers.PROJECTION_MAP);
			break;
		case UriMatcherCode.VIEW_HOTNEWS_USERS:
			qb.setTables(ViewHotNewsUsers.TABLE_NAME);
			qb.setProjectionMap(ViewHotNewsUsers.PROJECTION_MAP);
			break;
		case UriMatcherCode.VIEW_HOTNEWS_USERS_ID:
			qb.setTables(ViewHotNewsUsers.TABLE_NAME);
			qb.setProjectionMap(ViewHotNewsUsers.PROJECTION_MAP);
			qb.appendWhere(ViewHotNewsUsers._ID + "="
					+ uri.getPathSegments().get(1));
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		// Get the database and run the query
		Cursor c = qb.query(db, projection, selection, selectionArgs, null,
				null, sortOrder);

		// Tell the cursor what uri to watch, so it knows when its source data
		// changes
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public String getType(Uri uri) {
		int match = UriMatcherCode.match(uri);
		switch (match) {
		case UriMatcherCode.PROVINCE:
			return Province.CONTENT_TYPE;

		case UriMatcherCode.PROVINCE_ID:
			return Province.CONTENT_ITEM_TYPE;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public int bulkInsert(Uri uri, ContentValues[] values) {
		// TODO Auto-generated method stub
		return super.bulkInsert(uri, values);
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) {
		// Validate the requested uri
		ContentValues values = initialValues;
		ContentResolver cr = getContext().getContentResolver();
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int match = UriMatcherCode.match(uri);
		if (match < 0) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		String tableName = uri.getPathSegments().get(0);
		long rowId = db.insert(tableName, null, values);
		if (rowId > 0) {
			Uri noteUri = ContentUris.withAppendedId(uri, rowId);
			cr.notifyChange(noteUri, null);
			return noteUri;
		}

		if (initialValues != null) {
			values = new ContentValues(initialValues);
		} else {
			values = new ContentValues();
		}

		Long now = Long.valueOf(System.currentTimeMillis());

		if (values.containsKey(Province.NAME) == false) {
			Resources r = Resources.getSystem();
			values.put(Province.NAME, r.getString(android.R.string.untitled));
		}

		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public int delete(Uri uri, String where, String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		int match = UriMatcherCode.match(uri);
		if (match < 0) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		String tableName = uri.getPathSegments().get(0);
		switch (match) {
		case UriMatcherCode.PROVINCE_ID:
			String noteId = uri.getPathSegments().get(1);
			count = db.delete(tableName,
					Province._ID
							+ "="
							+ noteId
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
			break;
		default:
			count = db.delete(tableName, where, whereArgs);
			break;
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where,
			String[] whereArgs) {
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		int match = UriMatcherCode.match(uri);
		if (match < 0) {
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		String tableName = uri.getPathSegments().get(0);
		switch (match) {
		case UriMatcherCode.HOTNEWS_ID:
		case UriMatcherCode.COMPANY_USERS_ID:
		case UriMatcherCode.CITY_ID:
		case UriMatcherCode.PROVINCE_ID: {
			String id = uri.getPathSegments().get(1);
			count = db.update(tableName, values,
					BaseColumns._ID
							+ "="
							+ id
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
		}
			break;

		default:
			count = db.update(tableName, values, where, whereArgs);
			break;
		}

		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

}
